<?php

namespace catchAdmin\archives\controller;

use catchAdmin\archives\request\MonitorRequest;
use catcher\base\CatchController;
use catcher\base\CatchRequest;
use catcher\CatchResponse;
use app\common\model\CollectCase as CollectCaseModel;
use app\common\model\CollectClass as CollectClassModel;
use app\common\model\PatientInfo as PatientInfoModel;
use catchAdmin\archives\service\CollectService;
use catcher\Code;
use catcher\exceptions\FailedException;

class Collect extends CatchController
{
    protected $collectCase;

    public function __construct(CollectCaseModel $collectCase)
    {
        $this->collectCase = $collectCase;
    }

    /**
     * 收案列表
     *
     * @time 2020年01月09日
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(CatchRequest $request): \think\response\Json
    {

        $ret = $this->collectCase->getList();
        $result = array_merge($ret, ["code" => Code::SUCCESS, "message" => "success"]);
        return json($result);
    }

    /**
     *  创建收案分类
     * @return \think\response\Json
     */
    public function save_classify(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        if (empty($req['className'])) {
            throw new FailedException("菜单名称不能为空");
        }
        if (!empty($req['is_share']) == 1 && empty($req['manageList'])) {
            throw new FailedException("管理人员不能为空");
        }
        return CatchResponse::success((new CollectService())->addCollectClass($request->param()));
    }

    /**
     *  收案分类列表
     * @return \think\response\Json
     */
    public function list_classify(CatchRequest $request): \think\response\Json
    {
        $creatorId = $request->user()["id"];

        $type = $request->param("type", 1);
        $list = (new CollectClassModel())->getLists($type, $creatorId);
        //  array_unshift($list, ["className"=>"未分组","parent_id"=>"0","id"=>"-2","count"=>0]);
        return CatchResponse::success($list);
    }

    /**
     * 更新分类
     * @return \think\response\Json
     */
    public function up_classify($id, CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success((new CollectClassModel)->saveData($id, $request->param()));
    }

    /**
     * 删除分类
     * @return \think\response\Json
     */
    public function del_classify(CatchRequest $request): \think\response\Json
    {
        if (!(new CollectClassModel)->delClass($request->param('id'))) {
            return CatchResponse::fail('请先删除当前分组下的子分组');
        }
        return CatchResponse::success((new CollectClassModel)->delClass($request->param('id')));
    }

    /**
     * 查询条件收案患者
     * @return \think\response\Json
     */
    public function collect_patient(): \think\response\Json
    {
        $list = (new PatientInfoModel)->getWherePatient(1);
        $result = array_merge($list, ["code" => Code::SUCCESS, "message" => "success"]);
        return json($result);
    }

    /**
     * 保存收案患者
     * @return \think\response\Json
     */
    public function save(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();

        $patients = (new PatientInfoModel)->whereIn('id', $req['id'])->field('id,patientId,name,sex,bz,outList.attendingDoctorNo,inList.inchargeDoctorNo,hoList.inchargeDoctorNo')->select();

        //print_r($patients);exit();
        //添加多个收案患者
        $datas = [];
        foreach ($patients as $key => $val) {
            $data['pid'] = $val['id'];
            $data['sex'] = $val['sex'] ?? '';
            $data['name'] = $val['name'] ?? '';
            $data['patientId'] = $val['patientId'] ?? '';
            $data['creator_id'] = (int)$req['creator_id'];
            $data['deleted_at'] = (int)$req['deleted_at'];
            $data['diagnosis'] = $val['bz']['diagnoseArr'][0]['diagnose'] ?? '';
            $data['doctor_codes'] = [];

            if (isset($val['outList']['attendingDoctorNo']) && !empty($val['outList']['attendingDoctorNo'])) {
                $data['doctor_codes'][] = $val['outList']['attendingDoctorNo'];
            }
            if (isset($val['inList']['inchargeDoctorNo']) && !empty($val['inList']['inchargeDoctorNo'])) {
                $data['doctor_codes'][] = $val['inList']['inchargeDoctorNo'];
            }
            if (isset($val['hoList']['inchargeDoctorNo']) && !empty($val['hoList']['inchargeDoctorNo'])) {
                $data['doctor_codes'][] = $val['hoList']['inchargeDoctorNo'];
            }
            $datas[] = $data;
        }
        return CatchResponse::success((new CollectCaseModel)->saveAll($datas));
    }


    /**
     * 批量分组（作废）
     * @return \think\response\Json
     */
//    public function batch_grouping(CatchRequest $request): \think\response\Json
//    {
//        return CatchResponse::success((new CollectClassModel)->upGrouping($request->param()));
//    }

    /**
     * 标记死亡
     * @return \think\response\Json
     */
    public function mark_death(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        if (isset($req['is_all']) && $req['is_all'] === true) {
            $req['pid'] = (new PatientInfoModel())->getAllPatientIds($req['group_id'], request()->user()->id, 'id');
        }
        return CatchResponse::success((new PatientInfoModel())->upDeath($req));
    }

    /**
     * 取消收案
     * @return \think\response\Json
     */
    public function cancel(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        if (empty($req['id'])) {
            return CatchResponse::fail("请选择患者");
        }
        if (isset($req['is_all']) && $req['is_all'] === true) {
            $patientIds = (new PatientInfoModel())->getAllPatientIds($req['group_id'], request()->user()->id, 'patientId');
            $req['id'] = $this->collectCase->whereIn('patientId', $patientIds)->column('id');
        }
        $where[] = ['id', 'in', $req['id']];
        $pid = $this->collectCase->getKeyVal($where);
        (new CollectClassModel())->pullNode($pid);
        return CatchResponse::success($this->collectCase->delCase($req));
    }

    /**
     * 关注
     * @return \think\response\Json
     */
    public function follow(CatchRequest $request)
    {
        return CatchResponse::success((new CollectService)->followOperate($request->param('id')));
    }

    public function monitor(MonitorRequest $request): \think\response\Json
    {
        return CatchResponse::success((new CollectService())->monitor(request()->param()));
    }

    public function cancelMonitor(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success((new CollectService())->cancelMonitor(request()->param()));
    }


}
